//
//  LBUserAccout.swift
//  LBNewWeiBo
//
//  Created by bin on 15/10/29.
//  Copyright © 2015年 bin. All rights reserved.
//
/*
iOS保存数据的方式:
1.plist
2.偏好设置
3.归档
4.sqlite
5.CoreData
*/

import UIKit

class LBUserAccout: NSObject, NSCoding{

    
    // 有账号返回真
    class func userLogin() -> Bool {
        return LBUserAccout.loadAccount() != nil
    }
    
    
    // 用于调用 access_token ,接口授权后的access_token
    var access_token: String?
    
    // access_token 的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0 {
//         使用kvo监听值的改变
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
            print("expires_date:\(expires_date)")
        }
    }
        /// 当前授权用户的UID
    var uid: String?
    // 友好显示名称
    var name: String?
    
    // 用户头像
    var avatar_large: String?
    
        /// 当前时间
    var expires_date: NSDate?
    
    //MARK: - 构造方法
    /// KVC 字典转模型
    init(dict:[String: AnyObject]) {
        super.init()
        // kvc
        setValuesForKeysWithDictionary(dict)
        
        
    }
    
    // 当字典里的key在模型里面没有找到对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    
    // 输出属性
    override var description: String {
        
        return "access_token:\(access_token), expires_in\(expires_in), uid:\(uid), expires_date:\(expires_date), name:\(name), avatar_large:\(avatar_large)"
    }
    
    //MARK: - 加载用户信息
    // 不管加载是否成功，都要告诉调用者
    func loadUserInfo(finish: (error: NSError?) ->()) {
        LBNetworkTools.sharedInstance.loadUserInfo { (result, error) -> () in
            if error != nil || result == nil {
                finish(error: error)
                return
            }
            
            // 加载成功
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            // 保存到沙盒
            self.saveAccount()
            // 同步到内存中
            LBUserAccout.userAccount = self
            finish(error: nil)
        }
    }
    
    
    // 类方法访问属性需要定 static
    static let accountPath =
        NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/Account.plist"
    
    //MARK: -保存对象
    func saveAccount() {
        
        NSKeyedArchiver.archiveRootObject(self, toFile: LBUserAccout.accountPath)
        
    }
    
    //类方法反复问属性需要将属性定义为 static
    private static var userAccount: LBUserAccout?
    
    // 类方法访问属性定义成 static
    class func loadAccount() -> LBUserAccout? {
    
        if userAccount == nil {
        userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as?
            LBUserAccout
            print("\(userAccount)")
        }
        
        // 日期有问题
         if userAccount != nil && userAccount?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("账号有效")
            print("\(userAccount)")
            return userAccount
        }
        
        return nil
    }
    
    
    // MARK - 归档和解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token")as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        
        uid = aDecoder.decodeObjectForKey("uid")as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date")as? NSDate
        name = aDecoder.decodeObjectForKey("name")as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large")as? String
        
    }
}
